//
//  AppDelegate.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/18.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "AppDelegate.h"
#import "UIWindow+Extension.h"
#import "GFXNetworkHandle.h"
#import "ThirdConfig.h"
#import "HomeNetService.h"
#import "SZLAccountHelper.h"
#import <WXApi.h>
#import "CityGroupModel.h"
#import "CityModel.h"
#import "FMDBCityDataTool.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiManager.h"
#import "PayTool.h"
#import <EMSDK.h>
#import "AppDelegate+EaseMob.h"
#import <UMSocialCore/UMSocialCore.h>
#import "AppDelegate+Location.h"
#import "IQKeyboardManager.h"
#import "YYTextView.h"
#import <SDWebImageManager.h>
#import "ActivityNetWork.h"
#import "MBProgressHUD+MJ.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define EaseMobAppKey @"comeonsoft#funeath"
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    //环信初始化
//    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions appkey:EaseMobAppKey apnsCertName:nil otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:NO]}];
    [self setUpLocation];//定位初始化
    
    [self.window switchRootViewController];
    [self setConfig:application options:launchOptions];
    application.statusBarStyle = UIStatusBarStyleDefault;
    [self.window makeKeyAndVisible];
//    [self getCityList];
    [self setUpKeyBoardMgr];
#pragma -----------------------------
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification != nil) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dealwithInfomation:remoteNotification];
        });
    }
#pragma -----------------------------
    return YES;
}
- (void)setUpKeyBoardMgr
{
    [[IQKeyboardManager sharedManager] registerTextFieldViewClass:[YYTextView class] didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = NO;
    [IQKeyboardManager sharedManager].toolbarTintColor = [UIColor blackColor];
}
- (void)setConfig:(UIApplication *)application options:(NSDictionary *)launchOptions
{
    
    if ([SZLAccountHelper isAlreadyLogin]) {
        [SZLAccountHelper loadAlreadyInfo];//加载用户信息
    }
    [GFXNetworkHandle startMonitoring];
    [ThirdConfig setThirdConfig:application options:launchOptions delegate:self];
}

//下载城市列表
- (void)getCityList
{
    FMDBCityDataTool *tool = [FMDBCityDataTool shareTool];
    BOOL isExist = [tool isTableOK:@"t_city"];//数据库里面有数据就不请求了
    if (isExist) return;
    [HomeNetService getCityListWithresponse:^(BOOL success, NSString *msg, NSArray *banners) {
        if (success) {
            [[NSUserDefaults standardUserDefaults]setObject:banners forKey:CityList];
            dispatch_queue_t queue = dispatch_queue_create("shengzhuli", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
                NSMutableArray *cityModels = [NSMutableArray array];
                for (NSDictionary *dict in banners) {
                    CityGroupModel *model = [CityGroupModel cityGroupWithDict:dict];
                    [cityModels addObject:model];
                }
                //存数据库 查询方便
                [tool addCity:cityModels];
            });
        }
    }];
}
#pragma mark -----9.0之前的方法-----------------------
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if (activityId) {
        NSMutableDictionary *param  = [NSMutableDictionary dictionary];
        param[@"token"] = [SZLAccountHelper shareInstance].token;
        param[@"activityId"] = activityId;
        [ActivityNetWork getShareCountWithParame:param response:^(BOOL success, NSString *msg) {
            if (success) {
                [MBProgressHUD showSuccess:@"恭喜您获得活跃值"];
            }else {
                [MBProgressHUD showError:msg];
            }
        }];
    }

    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        return [WXApi handleOpenURL:url delegate:[PayTool shareTool]];
    }
    return result;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        if([sourceApplication isEqualToString:@"com.tencent.xin"]) {
            return [WXApi handleOpenURL:url delegate:[PayTool shareTool]];
        }else if([sourceApplication isEqualToString:@"com.alipay.iphoneclient"]) {
                [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                    NSLog(@"result = %@",resultDic);
                }];
            return YES;
        }
    }
    return result;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if (activityId) {
        NSMutableDictionary *param  = [NSMutableDictionary dictionary];
        param[@"token"] = [SZLAccountHelper shareInstance].token;
        param[@"activityId"] = activityId;
        [ActivityNetWork getShareCountWithParame:param response:^(BOOL success, NSString *msg) {
            
            if (success) {
//                [MBProgressHUD showSuccess:@"恭喜您获得活跃值"];
            }else {
//                [MBProgressHUD showError:msg];
            }
        }];
    }

    NSLog(@"host---%@",url.host);
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    if (!result) {
        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付，处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {// 钱包支付结果回调
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {//成功是9000
                    [[PayTool shareTool] checkPaySuccess];
                }else {
                    [MBProgressHUD showError:resultDic[@"memo"]];
                }
            }];
        }else if ([url.host isEqualToString:@"pay"]){
            [WXApi handleOpenURL:url delegate:[PayTool shareTool]];
        }
    } 
    return result;
}

//与环信冲突 只能去环信里面注册
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self dealwithInfomation:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [self dealwithInfomation:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)dealwithInfomation:(NSDictionary *)userInfo {
    [JPUSHService setBadge:0];
    [[NSNotificationCenter defaultCenter]postNotificationName:KPushNotification object:nil userInfo:userInfo];
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
}


- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
